package com.cjkj.applet.controller;

import com.cjkj.applet.domain.AppletAccount;
import com.cjkj.applet.service.AppletAccountService;
import com.cjkj.applet.util.WeChatUtil;
import com.cjkj.common.core.domain.R;
import com.cjkj.common.core.utils.DateUtils;
import com.cjkj.common.core.utils.StringUtils;
import com.cjkj.common.core.utils.bean.BeanUtils;
import com.cjkj.common.core.web.controller.BaseController;
import com.cjkj.system.api.domain.dto.APIWechatSessionDto;
import com.cjkj.system.api.domain.request.APIAppAccountReq;
import com.cjkj.system.api.model.AppletLoginUser;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 登录接口
 */
@RestController
@RequestMapping("/account")
public class LoginController extends BaseController {

    @Resource
    private AppletAccountService accountService;

    @PostMapping
    public R<?> addAccount(@RequestBody APIAppAccountReq apiAccount){
        AppletAccount account = new AppletAccount();
        BeanUtils.copyProperties(apiAccount,account);
        account.setCreateTime(DateUtils.getNowDate());
        Boolean addFlag = accountService.addAccount(account);
        if(addFlag){
            return R.ok("注册成功");
        }else {
            return R.fail("注册失败");
        }
    }

    @GetMapping("/getLoginUser")
    public R<AppletLoginUser> getUser(@RequestParam("openid") String openId){
        AppletAccount account = accountService.getAccountByOpenId(openId);
        AppletLoginUser user = new AppletLoginUser();
        if(StringUtils.isNull(account)){
            return R.ok();
        }
        BeanUtils.copyProperties(account,user);
        return R.ok(user);
    }

    @GetMapping("/getOpenId")
    public R<APIWechatSessionDto> getOpenId(@RequestParam("jsCode") String jsCode,
                                            @RequestParam("dataType") String dataType){
        return R.ok(WeChatUtil.getSession2Code(jsCode, dataType));
    }

}